let $FRAME_IMG = document.getElementById('frame_img');
let $PARAMS = document.getElementById('params');
let $VIEWER = document.getElementById('img-viewer');
let $POS = document.getElementById('pos');
let $INFO = document.getElementById('info')

let $THUMB = $$('#thumbs')
let $FRM_MAX = $$('#frm_max')

let st_frames = null
var D_TYPE = {'i': '.jpg', 'tif': '.tif'}

async function downfile() {
  let v = $TASKS.value
  let n = $FRAME_INPUT.value
  if (!v && !n) return
  let t = 'i'
  let tg = this.event.currentTarget
  if (tg.classList.contains('fa-download')) t = 'tif'
  try {
    downer(`/-/omsp.download?f=${v}&n=${n}&t=${D_TYPE[t]}`)
  } catch (e) {
    console.log(e)
  }
}

async function downer(url) {
  let resp = await fetch(url, {method: 'HEAD'})
  if (!resp.ok) {
    alert('文件不存在，请稍后下载！')
    return
  }
  let filename = resp.headers.get('content-disposition')
    .replace('attachment; filename="', '').replace('"', '')
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// 图片缩放、拖动功能
function init_viewer() {
  var viewer = $$('.x-viewer');
  var scale = $$('.x-scale');
  // 全局偏移位置记录
  var viewer_pos = {x0: 0, y0: 0, scale: 1};
  $FRAME_IMG.onload = (ev) => {
    var _s = 1. / Math.max($FRAME_IMG.offsetWidth / $VIEWER.offsetWidth, $FRAME_IMG.offsetHeight / $VIEWER.offsetHeight)
    viewer_pos.y0 = viewer_pos.x0 = 0;
    viewer_pos.scale = _s;
    scale.style.transform = 'translate(' + viewer_pos.x0 + 'px, ' + viewer_pos.y0 + 'px) scale(' + _s + ')';
  }
  // 位置换算公共方法
  var client2Viewer = function (p) {
    this.x1 = (p.clientX - viewer.offsetLeft - viewer_pos.x0);
    this.y1 = (p.clientY - viewer.offsetTop - viewer.offsetParent.offsetTop - viewer_pos.y0);
    _s = 1 / viewer_pos.scale;
    viewer_pos.x = this.x = this.x1 * _s;
    viewer_pos.y = this.y = this.y1 * _s;
  };

  // 缩放功能
  (viewer).onmousewheel = function (ev) {
    let _s = (ev.wheelDelta > 0) ? (viewer_pos.scale / .97) : (viewer_pos.scale * .97);
    if (_s > 0.1 && _s < 10) {
      let v_pos = new client2Viewer(ev || event);
      let _ss = 1 - (_s / viewer_pos.scale);
      viewer_pos.y0 += v_pos.y1 * _ss;
      viewer_pos.x0 += v_pos.x1 * _ss;
      viewer_pos.scale = _s;
      scale.style.transform = 'translate(' + viewer_pos.x0 + 'px, ' + viewer_pos.y0 + 'px) scale(' + _s + ')';
    }
    ev.preventDefault();
  };

  // 图像拖拽
  viewer.onmousedown = function (ev) {
    viewer.data = {x: viewer_pos.x0 - ev.clientX, y: viewer_pos.y0 - ev.clientY}
    scale.style.cursor = 'pointer'
  };
  window.onmouseup = function (ev) {
    scale.style.cursor = 'default'
    delete viewer.data
  };

  (viewer).onmousemove = function (ev) {
    // 图像拖拽
    var _d = viewer.data;
    if (_d) {
      viewer_pos.x0 = _d.x + ev.clientX;
      viewer_pos.y0 = _d.y + ev.clientY;
      scale.style.transform = 'translate(' + viewer_pos.x0 + 'px, ' + viewer_pos.y0 + 'px) scale(' + viewer_pos.scale + ')';
    }
  }
}

let ctrls = $('#ctrl input[type=range]');
ctrls.change(() => {
  let cst = ctrls[0].value
  let brt = ctrls[1].value
  let hue = ctrls[2].value
  let sfc = ctrls[3].value
  $VIEWER.style.filter = `brightness(${brt}) contrast(${cst}) hue-rotate(${hue}deg) saturate(${sfc})`
})
let reset = () => {
  $FRAME_IMG.onload()
  ctrls[0].value = 1
  ctrls[1].value = 1
  ctrls[2].value = 0
  ctrls[3].value = 1
  $VIEWER.style.filter = ''
}


class CamViewer extends Realtime {
  constructor(key, params) {
    super(key, $STATION, params)
    this.viewer = document.body
    // this.params = params
    this.thumbs = $('.thumbs')
    this.$frmr.onchange = this.frm_rang_change.bind(this)
    // this.$frmi.onchange = this.frm_inpt_change.bind(this)
    this.tasks.onchange = this.onTask.bind(this)
    this.$day.onchange = this.day_change.bind(this)
    $('#thumbs').on('click', 'div', this.thumb_change.bind(this))
    // $('#frm_img_table').on('click', this.history.bind(this))
    $FRAME_IMG.onmousemove = this.img_mouse_move.bind(this);
    this.$mode.onchange = this.onMode.bind(this)
    init_viewer()
  }

  params(v) {
    $INFO.innerHTML = ''
    this.set_img(v);
    super.params(v);
  }

  reset() {
    super.reset()
    $FRAME_IMG.src = ''
  }

  set_frmNo(v) {
    this.$frmr.value = this.$frmi.value = v
  }

  img_mouse_move(ev) {
    let x = ev.offsetX.toString();
    let y = ev.offsetY.toString()
    $POS.innerText = `x: ${x.padStart(4, ' ')} , y: ${y.padStart(4, ' ')} `
    if (this.ws_img) {
      if(this.ws_img.readyState==1){
        this.ws_img.send(`${x},${y}`);
      }else{
        console.warn("x:"+x+",y:"+y)
      }

    }
  }

  async thumb_change(v) {
    this.to_frm_view()
    let target = v.currentTarget
    this.active_thumb(target)
    let frm_no = parseInt(target.getAttribute('data'))
    this.set_frmNo(frm_no)
    this.clear_frame()
    this.load_frm()
  }

  async frm_inpt_change() {
    let i_v = parseInt(this.$frmi.value)
    let max = parseInt(this.$frmr.max)
    let min = parseInt(this.$frmr.min)
    this.set_frmNo(i_v < min ? min : (i_v > max ? max : i_v))
    await this.frm_rang_change()
  }

  async frm_rang_change() {
    await this.load_frm()
    this.jump_thumb()
  }

  clear_frm_all() {
    this.init_frm_input()
    this.clear_frame()
    this.clear_thumbs()
    $PARAMS.innerHTML = ''
  }

  async day_change() {
    this.kill_realtime()
    this.clear_frm_all()
    this.to_frm_table_view()
    await this.load_task(this.$day.value, true)

  }

  load_thumbs_and_frminput() {
    this.filter_frames()
    if (st_frames) st_frames(this.frames_ori);
  }

  filter_frames(mode) {
    super.filter_frames(mode)
    this.set_thumbs()
  }

  init_frm_input() {
    let default_no = 0
    let no_no = 0
    this.$frmi.textContent = default_no
    this.$frmi.value = default_no
    this.$frmr.value = default_no
    this.$frmr.max = no_no
    this.$frmr.min = no_no
    this.$frmi.textContent = ''
    $FRM_MAX.textContent = ''
  }


  set_img(vv) {
    this.cur_frame = vv
    $FRAME_IMG.src = `/-/omsp.frm_img?f=${this.cur_task}&n=${vv.name}.jpg`
    // this.ws_img_conn(vv.name)
    this.ws_img_conn()
  }

  ws_img_conn() {
    if (this.ws_img) this.close_ws_img()

    let  n = this.frames[parseInt(this.$frmr.value)].name
    console.error("ws_img connect:"+n)
    this.ws_img = new WsEx('omsp.rt?f=' + this.cur_task + "&n=" + n)
    this.ws_img.onmessage = this.msg_img.bind(this)
    this.ws_img.onerror = this.msg_img_error.bind(this)
    this.ws_img.onclose = this.close_ws_img.bind(this)
  }
  close_ws_img(){
    if(this.ws_img){
      this.ws_img.close()
    }
    delete this.ws_img
  }
  msg_img_error(){
    this.close_ws_img()
    if (this.ws_img_timeoutid) clearTimeout(this.ws_img_timeoutid)
    this.ws_img_timeoutid = setTimeout(this.ws_img_conn.bind(this), 3000)
  }
  msg_img(d) {
    $INFO.innerHTML = d.data
  }

  async set_thumbs() {
    $THUMB.innerHTML = this.frames.map(v => {
      let frm = v.frm_;
      return `<div data=${frm} class="thum-box">
                  <div class="head"><label>序号 ${frm}</label><label> ${BJT(v.st).slice(0, 19)}</label></div>
                  <img src="/-/omsp.thumb?f=${this.cur_task}&n=${v.name}.jpg">
                </div>`
    }).join('')
  }

  set_params(tbody) {
    $PARAMS.innerHTML = tbody;
  }


  clear_frame() {
    this.set_params('')
    $FRAME_IMG.src = ''
  }

  async load_frm() {
    let frm_no = this.$frmr.value
    this.params(this.frames[frm_no])
  }

  jump_thumb() {
    // 首次从实时快视切换到历史回放时，应先加载缩略图，再选择缩略图
    let thumb = $THUMB.children[this.$frmr.value]
    if (thumb) {
      this.active_thumb(thumb)
      thumb.scrollIntoView()
    }
  }

  active_thumb(v) {
    $('#thumbs > div').removeClass('active')
    v.classList.add('active')
  }

  async onTask() {
    this.cur_task = this.$task.value
    await this.history()
  }

  async history() {
    super.history()
    this.to_frm_table_view()
    this.kill_realtime()
    this.clear_frm_all()
    await this.load_thumbs_and_frminput()
  }

  kill_realtime() {
    this.real_task = {}
  }

  to_frm_table_view() {
    this.viewer.className = 'M2'
    this.loaded_frms_flag = false
  }

  to_frm_view() {
    this.viewer.className = 'M3'
    this.loaded_frms_flag = true
  }


  async realtime() {
    super.realtime()
    this.viewer.className = 'M1'
    this.loaded_frms_flag = false
    this.clear_thumbs()
  }

  clear_thumbs() {
    $THUMB.innerHTML = ''
  }

  async newtask(d) {
    let tsk = await super.newtask(d);
    let day = this.$day.value = tsk.date()
    this.load_thumbs_and_frminput()
  }

  newframe(d) {
    super.newframe(d);
    if (st_frames) {
      st_frames(this.frames_ori)
    } else {
      this.renderMode()
      this.filter_frames()
    }
    this.$frmi.value = this.$frmr.value = this.frame_max = d.frm
    this.params(d);
  }
}


